import { getCookie,removeCookie } from './cookie.js'
const xhr = require("xhr")
const GUID = () => {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }
    return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
}



const req = (method,url,params) => {
    Object.keys(params).map((key,i) => {
        if (params[key] === "") {
            delete params[key]
        }
    })
    return new Promise((reslove,reject) => {
        xhr({
            method: method,
            body: JSON.stringify(params),
            uri: url,
            headers: {
                "token": getCookie("token"),
                // "refreshToken": getCookie("refreshToken"),
                "Content-Type": "application/json",
            }
        },(err, res, body) => {
            if (err) {
                reject(err)
            } else {
                try {
                    body = JSON.parse(body);
                    if (body.code === "-3") {
                        removeCookie("token")
                        removeCookie("refreshToken")
                        setTimeout(() => {
                            vueInstance.$router.push('/login')
                        }, 100);
                    }
                    reslove(body)
                } catch (error) {
                    reject(res)
                }
            }
        })
    })
}
const get = (url,params) => req('get',url,params);
const post = (url,params) => req('post',url,params);
export { post, get }
